local tc = transition.cancel
local tt = transition.to
local tf = transition.from

local function addMotion(self, motionName, transition)
    self.Motion[motionName] = transition
end

local function removeMotion(self, motionName)
    if self.Motion[motionName] then
        tc(self.Motion[motionName])
        self.Motion[motionName] = nil
    end
end

local function clear(self)
    if not self.Motion then return end

    for i=1, #self.Motion, 1 do
        tc(self.Motion[i])
    end
end

local function completeHandler(self, motionName, remove)
    self:dispatchEvent{name="Motion"; motion=motionName, action="complete"}
    if remove then
        self:removeSelf()
        self = nil
    end
end

local function fadeOut(self, time, delay, remove)
	local motionName = "fadeOut";
   
    self.isVisible, self.alpha 	= true, 1
    local t = tt(self, {
        time=time, 
        delay=delay, 
        transition=easing.outExpo, 
        alpha=0, 
        onComplete=function(event) completeHandler(self, motionName, remove) end}))
    addMotion(self, motionName, t)
end

local function fadeIn(self, time, delay)
    local motionName = "fadeIn";

    self.isVisible, self.alpha  = true, 0
    local t = tt(self, {   
        time=time, 
        delay=delay, 
        transition=easing.outExpo, 
        alpha=1, 
        onComplete=function(event) completeHandler(self, motionName) end})
    addMotion(self, motionName, t)
    
end

local motion = {}
function motion.injectMotions(object)
	
    if type(object) ~= "table" then
        error('object is not of type table')
    end

	if not object.Motion then
		object.Motion 	= {}
	end

    object.MotionFadeOut   = fadeOut
    object.MotionFadeIn    = fadeIn
    object.MotionClear     = clear
end
return motion